package com.example.anni.zhuzhoujia.xiaowan;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.anni.zhuzhoujia.R;
import com.lhh.ptrrv.library.PullToRefreshRecyclerView;

import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Anni on 2016/7/6.
 */
public class MyCollectionActivity extends AppCompatActivity {
    private PullToRefreshRecyclerView mPtrrv;
    private List<Map<String, String>> mDatas;
    private MyCollectionAdapter mAdapter;
    private JSONArray arr;
    ;
    private TextView tvClickEdit;
    private TextView tvClickOver;
    private static final int DEFAULT_ITEM_SIZE = 10;
    private static final int ITEM_SIZE_OFFSET = 5;

    private static final int MSG_CODE_REFRESH = 0;
    private static final int MSG_CODE_LOADMORE = 1;

    private static final int TIME = 1000;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_collection_activity);
        initData();
        initView();
        tvClickEdit = (TextView) findViewById(R.id.tv_click_edit);
        tvClickOver = (TextView) findViewById(R.id.tv_click_over);

    }

    private void initView() {
        mPtrrv = (PullToRefreshRecyclerView) findViewById(R.id.prrv_my_collection);
        mPtrrv.setSwipeEnable(true);
        //加载条
        DemoLoadMoreView loadMoreView = new DemoLoadMoreView(this, mPtrrv.getRecyclerView());
        loadMoreView.setLoadmoreString(getString(R.string.loadmore));
        loadMoreView.setLoadMorePadding(100);
        //线性管理器
        LinearLayoutManager layoutManager =
                new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mPtrrv.setLayoutManager(layoutManager);
        mPtrrv.setPagingableListener(new PullToRefreshRecyclerView.PagingableListener() {
            @Override
            public void onLoadMoreItems() {
                mHandler.sendEmptyMessageDelayed(MSG_CODE_LOADMORE, TIME);
            }
        });
        mPtrrv.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mHandler.sendEmptyMessageDelayed(MSG_CODE_REFRESH, TIME);
            }
        });
        //设置下划线
        mPtrrv.getRecyclerView().addItemDecoration(new DividerItemDecoration(this,
                DividerItemDecoration.VERTICAL_LIST));
        //设置动画
        mPtrrv.getRecyclerView().setItemAnimator(new DefaultItemAnimator());
        mPtrrv.addHeaderView(View.inflate(this, R.layout.read_history_header, null));
        mPtrrv.setEmptyView(View.inflate(this, R.layout.read_history_empty_view, null));
        mPtrrv.removeHeader();
        mPtrrv.setLoadMoreFooter(loadMoreView);
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == MSG_CODE_REFRESH) {
                if (arr.size() < 10) {
                    mAdapter.setCount(arr.size());
                } else {
                    mAdapter.setCount(DEFAULT_ITEM_SIZE);
                }
                mPtrrv.setOnRefreshComplete();
                mPtrrv.onFinishLoading(true, false);
            } else if (msg.what == MSG_CODE_LOADMORE) {
                if (arr.size() - mAdapter.getItemCount() >= 5) {
                    // Log.e("mAdapter", mAdapter.getItemCount()+ITEM_SIZE_OFFSET+"");
                    mAdapter.setCount(mAdapter.getItemCount() + ITEM_SIZE_OFFSET);
                    mPtrrv.onFinishLoading(true, false);
                } else if (arr.size() - mAdapter.getItemCount() < 5 && arr.size() - mAdapter.getItemCount() > 0) {
                    mAdapter.setCount(mAdapter.getItemCount() + arr.size() - mAdapter.getItemCount());
                    Log.e("mAdapter", mAdapter.getItemCount() + arr.size() - mAdapter.getItemCount() + "");
                    mPtrrv.onFinishLoading(true, false);
                } else if (arr.size() - mAdapter.getItemCount() < 0) {
                    mAdapter.setCount(arr.size());
                } else {
                    //Log.e("mAdapter", "没有更多加载"+"");
                    //over
                    Toast.makeText(MyCollectionActivity.this, "没有更多加载", Toast.LENGTH_SHORT).show();
                    mPtrrv.onFinishLoading(false, false);
                }
            }
        }
    };


    private void initData() {
        mDatas = new ArrayList<>();
        RequestParams params =
                new RequestParams("http://tr.zzapi.gson.cn/api/user/favorites");
        String uid = getIntent().getStringExtra("uid");

        params.addQueryStringParameter("page", "1");
        params.addQueryStringParameter("rows", "30");
        params.addQueryStringParameter("uid", uid);
        x.http().get(params, new CallBackAdapter<String>() {
            @Override
            public void onSuccess(String s) {
                //Log.e("s/**-*-", s);
                JSONObject obj = JSON.parseObject(s);
                Boolean success = obj.getBoolean("success");
                if (success) {
                    arr = obj.getJSONArray("data");
                    Log.e("arr----------", arr.size() + "");
                    for (int i = 0; i < arr.size(); i++) {
                        Map<String, String> map = new HashMap<>();
                        map.put("title", arr.getJSONObject(i).getString("title"));
                        map.put("id", arr.getJSONObject(i).getString("id"));
                        map.put("views", arr.getJSONObject(i).getString("views"));
                        map.put("dateline", arr.getJSONObject(i).getString("dateline"));
                        map.put("source", arr.getJSONObject(i).getString("source"));
                        map.put("isDeleted", "1");
                        mDatas.add(map);
                    }

                    mAdapter = new MyCollectionAdapter(MyCollectionActivity.this, mDatas);
                    if (arr.size() < 10) {
                        mAdapter.setCount(arr.size());
                    } else {
                        mAdapter.setCount(DEFAULT_ITEM_SIZE);
                    }
                    mPtrrv.setAdapter(mAdapter);
                    mPtrrv.onFinishLoading(true, false);
                    mAdapter.setOnItemClickListener(new OnItemClickListener() {
                        @Override
                        public void OnItemClick(View view, int position) {

                        }

                        @Override
                        public void OnItemLongClick(View view, final int position) {

                        }
                    });
                }
            }

            @Override
            public void onError(Throwable throwable, boolean b) {
                throwable.printStackTrace();
            }
        });
    }

    class MyCollectionAdapter extends RecyclerView.Adapter<MyViewHold2> {
        private List<Map<String, String>> mDatas;
        private Context mContext;
        private LayoutInflater mInflater;
        protected int mCount = 0;

        public MyCollectionAdapter(Context mContext, List<Map<String, String>> mData) {
            this.mDatas = mData;
            this.mContext = mContext;
            mInflater = LayoutInflater.from(mContext);
        }

        //自定义接口
        private OnItemClickListener mOnItemClickListener;

        public void setOnItemClickListener(OnItemClickListener listener) {
            this.mOnItemClickListener = listener;

        }

        public void setCount(int count) {
            mCount = count;
        }

        @Override
        public MyViewHold2 onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = mInflater.inflate(R.layout.my_collection, parent, false);
            MyViewHold2 viewHold2 = new MyViewHold2(view);
            return viewHold2;
        }

        @Override
        public void onBindViewHolder(final MyViewHold2 holder, final int position) {
            holder.tvMyCollectionTitle.setText(mDatas.get(position).get("title"));
            holder.tvMyCollectionSource.setText("来源：" + mDatas.get(position).get("source"));
            holder.tvMyCollectionViews.setText("阅读：" + mDatas.get(position).get("views"));
            if (mDatas.get(position).get("isDeleted").equals("1")) {
                holder.btnClickDelete.setVisibility(View.GONE);
            } else {
                holder.btnClickDelete.setVisibility(View.VISIBLE);
            }
            tvClickEdit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    tvClickEdit.setVisibility(View.GONE);
                    tvClickOver.setVisibility(View.VISIBLE);
                    for (Map<String, String> a : mDatas) {
                        a.put("isDeleted", "2");
                    }
                    notifyDataSetChanged();
                    tvClickOver.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            tvClickEdit.setVisibility(View.VISIBLE);
                            tvClickOver.setVisibility(View.GONE);
                            for (Map<String, String> a : mDatas) {
                                a.put("isDeleted", "1");
                            }
                            notifyDataSetChanged();
                        }
                    });
                }
            });

            //点击删除
            holder.btnClickDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    RequestParams params =
                            new RequestParams("http://tr.zzapi.gson.cn/api/news/favorites");
                    String id = mDatas.get(position).get("id");
                    params.addQueryStringParameter("id", id);
                    x.http().get(params, new CallBackAdapter<String>() {
                        @Override
                        public void onSuccess(String s) {
                            JSONObject obj = JSON.parseObject(s);
                            Boolean success = obj.getBoolean("success");
                            if (success) {
                                Toast.makeText(MyCollectionActivity.this,
                                        obj.getString("message"), Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                    removeRecycle(position);
                }
            });

            //回调接口
            if (mOnItemClickListener != null) {
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int layoutPosition = holder.getLayoutPosition();
                        mOnItemClickListener.OnItemClick(holder.itemView, layoutPosition);
                    }
                });
                holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        int layoutPosition = holder.getLayoutPosition();
                        mOnItemClickListener.OnItemLongClick(holder.itemView, layoutPosition);
                        return false;
                    }
                });
            }
        }

        @Override
        public int getItemCount() {
            return mDatas.size();
        }

        public void removeRecycle(int position) {
            mDatas.remove(position);
            notifyItemRemoved(position);
        }

    }
}

class MyViewHold2 extends RecyclerView.ViewHolder {
    TextView tvMyCollectionTitle; // 标题
    TextView tvMyCollectionSource;  // 来源
    TextView tvMyCollectionViews;  //  阅读数
    Button btnClickDelete;  //删除按钮

    public MyViewHold2(View itemView) {
        super(itemView);
        tvMyCollectionTitle = (TextView) itemView.findViewById(R.id.tv_my_collection_title);
        tvMyCollectionSource = (TextView) itemView.findViewById(R.id.tv_my_collection_source);
        tvMyCollectionViews = (TextView) itemView.findViewById(R.id.tv_my_collection_views);
        btnClickDelete = (Button) itemView.findViewById(R.id.btn_click_delete);
    }
}
